//
//  FirstPageViewController.m
//  SXHomeTownClub
//
//  Created by 周思扬 on 2018/5/28.
//  Copyright © 2018年 jsx. All rights reserved.
//

#import "FirstPageViewController.h"
#import "DiscuzBannelTableViewCell.h"
#import "FirstPageNavigationBarView.h"
#import "MainThemeTableViewCell.h"
#import "DiscuzMainTableViewCell.h"
#import "DiscuzMainTableViewCell2.h"
#import "PostBaseData.h"

@interface FirstPageViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    DiscuzBannelTableViewCell * bannelcell;
    FirstPageNavigationBarView * navbarView;
    BOOL hasNewData;
}
@property(nonatomic, assign) int currentPage;

@property(nonatomic, strong) PostBaseData *bannelData;
@property(nonatomic, strong) PostBaseData *groupData;
@property(nonatomic, strong) PostBaseData *currentMainData;

@property(nonatomic, strong) NSMutableArray *layoutData;
@property(nonatomic, strong) NSMutableArray *mainDataList;
@property(nonatomic, strong) NSMutableArray *bannelImgsData;
@property(nonatomic, strong) NSMutableArray *bannelImgsIdData;

@end

@implementation FirstPageViewController

#pragma mark -UITableView代理方法

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.layoutData.count+self.mainDataList.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * cellName;
    if(indexPath.row<self.layoutData.count)
    {
        cellName = self.layoutData[indexPath.row];
    }
    
    if([cellName isEqualToString:@"bannel"])
    {
    bannelcell= [tableView dequeueReusableCellWithIdentifier:@"discuzBannelTableViewCell"];
    bannelcell.selectionStyle=UITableViewCellSelectionStyleNone;
    if(self.bannelImgsData.count>0)
    {
         bannelcell.bannelImgs=self.bannelImgsData;
         [bannelcell adjustPosition];
    }
    @weakify(self);
    bannelcell.block = ^(int index) {
        if(self.bannelImgsIdData.count>index)
        {
            @strongify(self);
            NSString * tid=self.bannelImgsIdData[index];
            [self pushToPostDetail:tid anduid:@"5" andfrom_type:@"1"];
        }
    };
    return bannelcell;
    }else if([cellName isEqualToString:@"theme"])
    {
        MainThemeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"mainThemeTableViewCell"];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.baseData=self.groupData;
        cell.block = ^(NSIndexPath *indexPath) {
            if(self.groupData.msg.count>indexPath.row)
            {
                PostBaseData_summary * cellData=self.groupData.msg[indexPath.row];
                NSString * tid=cellData.tid;
                [self pushToPostDetail:tid anduid:@"55" andfrom_type:@"1"];
            }
            
        };
        return cell;
    }else
    {
        PostBaseData_summary * celldata=self.mainDataList[indexPath.row-self.layoutData.count];
        if(celldata.pic.count>1)
        {
            DiscuzMainTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"discuzMainTableViewCell"];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.baseData=celldata;
            return cell;
        }else
        {
            DiscuzMainTableViewCell2 * cell = [tableView dequeueReusableCellWithIdentifier:@"discuzMainTableViewCell2"];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.baseData=celldata;
            return cell;
        }
    }
    
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"登录"message:@"登录后才能查看"
                                                                       preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        LoginViewController * vc=[LoginViewController shareLoginViewController];
        [self presentViewController:vc animated:vc completion:nil];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:sureAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
    return;
    
    if(indexPath.row>=self.layoutData.count)
    {
        PostBaseData_summary * celldata=self.mainDataList[indexPath.row-self.layoutData.count];
        [self pushToPostDetail:celldata.tid anduid:@"5" andfrom_type:@"1"];
    }
}


-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(scrollView==self.tableview)
    {
        CGFloat height = scrollView.frame.size.height;
        CGFloat contentYoffset = scrollView.contentOffset.y;
        CGFloat distance = scrollView.contentSize.height-height-contentYoffset;
        if (distance<=0&&hasNewData) {
            self.currentPage++;
            [self getInitData];
        }
    }
}

-(void)setMainTableViewFooterView
{
    if(hasNewData)
    {
        TableViewOfRefreshFooterView * footer = [TableViewOfRefreshFooterView shareView];
        footer.frame=CGRectMake(0, 0, SDScreenWidth, 60);
        self.tableview.tableFooterView=footer;
    }else
    {
        TableViewOfRefreshFooterView2 * footer2 = [TableViewOfRefreshFooterView2 shareView];
        footer2.frame=CGRectMake(0, 0, SDScreenWidth, 60);
        self.tableview.tableFooterView=footer2;
    }
}


#pragma mark - 生命周期

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
-(void)addSubViews
{
    self.tableview.delegate=self;
    self.tableview.dataSource=self;
    [self.tableview registerNib:[UINib nibWithNibName:@"DiscuzBannelTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"discuzBannelTableViewCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"MainThemeTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"mainThemeTableViewCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"DiscuzMainTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"discuzMainTableViewCell"];
    [self.tableview registerNib:[UINib nibWithNibName:@"DiscuzMainTableViewCell2" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"discuzMainTableViewCell2"];
    
    self.tableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.tableview.estimatedRowHeight = 200;
    self.tableview.rowHeight = UITableViewAutomaticDimension;
    self.tableview.contentInset=UIEdgeInsetsMake(0, 0, self.tabBarController.tabBar.bounds.size.height, 0);
    
    [self.tableview addPullToRefreshWithActionHandler:^{
        self.currentPage=1;
        [self getInitData];
        [self.tableview.pullToRefreshView stopAnimating];
    }];
    
    navbarView=[FirstPageNavigationBarView shareView];
    navbarView.frame=CGRectMake(0, 0, SDScreenWidth, self.navigationController.navigationBar.bounds.size.height+StatusBarHeight);
    [self.view addSubview:navbarView];
    
    @weakify(self);
    [RACObserve(self.tableview,contentOffset)subscribeNext:^(id x) {
        @strongify(self);
        CGPoint cp =[x CGPointValue];
        self->navbarView.frame=CGRectMake(0, 0, SDScreenWidth, self.navigationController.navigationBar.bounds.size.height+StatusBarHeight);
        CGFloat navbarheight = self.navigationController.navigationBar.bounds.size.height+StatusBarHeight;
        if(cp.y/navbarheight>=1)
        {
            self->navbarView.bgview.backgroundColor=ThemeColor;
        }else
        {
            double radio=0.0;
            if(cp.y>=0)
            {
                radio=cp.y/navbarheight;
            }
            self->navbarView.bgview.backgroundColor=[ThemeColor colorWithAlphaComponent:radio];
        }
    }];
    
    //全局配置信息
    self.currentPage=1;
    self.needNoNetTips=YES;
    self.needNoTableViewDataTips=YES;
    self.baseTableview=self.tableview;
}

-(void)getInitData
{
    if(self.currentPage==1)
    {
        [self getBannelData];
        [self getGroupData];
        [self getMainListData];
    }else
    {
        [self getMainListData];
    }
}

-(void)nonetstatusGetData
{
    self.currentPage=1;
    [self getInitData];
}

-(void)nodatasGetData
{
    self.currentPage=1;
    [self getInitData];
}

-(void)setNavigationBar
{
    
}


#pragma mark - 接口访问

-(void)getBannelData
{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [JSXHttpTool Get:Interface_FirstPageBannel params:params success:^(id json) {
        NSNumber * returnCode = json[@"code"];
        if([returnCode intValue]==1)
        {
            self.bannelData=[PostBaseData mj_objectWithKeyValues:json];
            for(int i=0;i<self.bannelData.msg.count;i++)
            {
                PostBaseData_summary * data=self.bannelData.msg[i];
                if(data.pic.count>0)
                {
                    [self.bannelImgsData addObject:data.pic.firstObject];
                    [self.bannelImgsIdData addObject:data.tid];
                }
            }
            [self.tableview reloadData];
            
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void)getGroupData
{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [JSXHttpTool Get:Interface_FirstPageGroup params:params success:^(id json) {
        NSNumber * returnCode = json[@"code"];
        if([returnCode intValue]==1)
        {
            self.groupData=[PostBaseData mj_objectWithKeyValues:json];
            [self.tableview reloadData];
            
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void)getMainListData
{
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"page"]=@(self.currentPage);
    [JSXHttpTool Get:Interface_FirstPageMainList params:params success:^(id json) {
        NSNumber * returnCode = json[@"code"];
        if([returnCode intValue]==1)
        {
            if(self.currentPage==1)
            {
                if(self.mainDataList.count>0)
                {
                    [self.mainDataList removeAllObjects];
                }
                self.currentMainData=[PostBaseData mj_objectWithKeyValues:json];
                if(self.currentMainData.msg.count==0)
                {
                    self->hasNewData=NO;
                    [self setMainTableViewFooterView];
                }else
                {
                    self->hasNewData=YES;
                    [self setMainTableViewFooterView];
                }
                self.mainDataList=self.currentMainData.msg;
                [self.tableview reloadData];
            }else
            {
                self.currentMainData=[PostBaseData mj_objectWithKeyValues:json];
                if(self.currentMainData.msg.count==0)
                {
                    self->hasNewData=NO;
                    [self setMainTableViewFooterView];
                }else
                {
                    self->hasNewData=YES;
                    [self setMainTableViewFooterView];
                }
                [self.mainDataList addObjectsFromArray:self.currentMainData.msg];
                [self.tableview reloadData];
            }
        }else
        {
            if(self.currentPage>1)
            {
                self.currentPage--;
            }
        }
    } failure:^(NSError *error) {
        if(self.currentPage>1)
        {
            self.currentPage--;
        }
    }];
}

#pragma mark - LazyLoad

-(NSMutableArray *)bannelImgsData
{
    if(_bannelImgsData==nil)
    {
        _bannelImgsData=[NSMutableArray array];
    }
    return _bannelImgsData;
}

-(NSMutableArray *)bannelImgsIdData
{
    if(_bannelImgsIdData==nil)
    {
        _bannelImgsIdData=[NSMutableArray array];
    }
    return _bannelImgsIdData;
}

-(NSMutableArray *)layoutData
{
    if(_layoutData==nil)
    {
        _layoutData=[NSMutableArray array];
        [_layoutData addObject:@"bannel"];
        [_layoutData addObject:@"theme"];
    }
    return _layoutData;
}

-(NSMutableArray *)mainDataList
{
    if(_mainDataList==nil)
    {
        _mainDataList=[NSMutableArray array];
    }
    return _mainDataList;
}

@end
